import { defineStore } from 'pinia'
import api from '@/api/http'

// 初始风格预设（后续可拆文件）
const STYLE_PRESETS = [
  { key: 'classical', label: '古典', desc: '卷轴气韵 / 雅致留白' },
  { key: 'shanshui', label: '山水', desc: '群峦云岚 / 氤氲意境' },
  { key: 'gongbi', label: '工笔', desc: '线条精细 / 层次严谨' },
  { key: 'qinglv', label: '青绿', desc: '青绿设色 / 丹青晕染' },
  { key: 'shuimo', label: '水墨', desc: '写意墨韵 / 黑白层阶' },
  { key: 'xieyi', label: '写意', desc: '笔简意远 / 神韵突出' },
  { key: 'jianbi', label: '简笔', desc: '减笔概括 / 线意相生' },
  { key: 'qinghua', label: '青花', desc: '青花瓷釉 / 古雅留白' }
]

export const useAiImageStore = defineStore('aiImage', {
  state: () => ({
    prompt: '',
    basePromptSnapshot: '',
    style: 'classical',
  // 当前模型仅支持 1024*1024，临时锁定
  sizeFixed: '1024x1024',
    generating: false,
    sessionImages: [], // 当前会话生成的图像
    history: {
      items: [],
      page: 1,
      pageSize: 24,
      total: 0,
      loading: false,
      favoritesOnly: false,
      styleFilter: null,
      keyword: '',
      endReached: false
    },
    stats: null,
    linkContext: { bookId: null, chapter: null, paragraph: null, excerpt: '', returnUrl: '' },
    initializedFromRoute: false
  }),
  getters: {
    hasLinkContext: (s) => !!s.linkContext.excerpt,
    promptEdited: (s) => s.prompt && s.prompt !== s.basePromptSnapshot,
  stylePresets: () => STYLE_PRESETS,
  styleMetaMap: () => STYLE_PRESETS.reduce((m,s)=>{m[s.key]=s;return m;}, {})
  },
  actions: {
    initFromRoute(query, { force = false } = {}) {
      if (this.initializedFromRoute && !force) {
        // 若已有上下文但本次 query 与现有不同，则允许重新初始化
        const { book, chapter, para, sec, excerpt } = query || {}
        if (book && chapter && para != null && sec != null) {
          const changed = (
            Number(book) !== Number(this.linkContext.bookId) ||
            Number(chapter) !== Number(this.linkContext.chapter) ||
            Number(para) !== Number(this.linkContext.paragraph) ||
            Number(sec) !== Number(this.linkContext.section)
          )
          if (!changed) return
        } else {
          return
        }
      }
      // 解析链接上下文（M3）
      try {
        const { book, bt, chapter, sec, para, excerpt, trunc, return: ret } = query || {}
        if (book && chapter && sec != null && para != null && excerpt) {
          const decodedExcerpt = decodeURIComponent(excerpt)
          const decodedTitle = bt ? decodeURIComponent(bt) : ''
          this.linkContext = {
            bookId: Number(book) || book,
            chapter: Number(chapter) || chapter,
            paragraph: Number(para) || para,
            section: Number(sec) || sec,
            excerpt: decodedExcerpt,
            truncated: trunc === '1' || trunc === 1,
            returnUrl: ret ? decodeURIComponent(ret) : ''
          }
          // 构造初始提示词模板
          const chapterLabel = this.linkContext.chapter
          const paraLabel = this.linkContext.paragraph
          const titlePart = decodedTitle ? `《${decodedTitle}》` : '原文'
          const header = `【摘自${titlePart} 第${chapterLabel}章 第${paraLabel}段】`
          const promptTemplate = `${header}\n${decodedExcerpt}\n请以古典意境风格描绘其核心画面。`
          this.prompt = promptTemplate
          this.basePromptSnapshot = promptTemplate
          this.style = 'classical'
        }
      } catch (e) {
        console.warn('[aiImageStore] route init parse failed', e)
      }
      this.initializedFromRoute = true
    },
    async generateImage() {
      if (!this.prompt || this.generating) return
      this.generating = true
      try {
        // 后端 size 接口格式用 * 号替换 x
        const sizeParam = this.sizeFixed.toLowerCase().includes('*')
          ? this.sizeFixed.toLowerCase()
          : this.sizeFixed.toLowerCase().replace(/x/g, '*')
  const resp = await api.post('/api/ai/generate-image', {
          prompt: this.prompt,
            style: this._mapStyleToLabel(this.style),
          size: sizeParam
        })
        const data = resp.data
        if (data?.image_url) {
          this.sessionImages.unshift({
            id: Date.now(), // 临时ID（真实历史刷新后替换）
            image_url: data.image_url,
            prompt: this.prompt,
            style: this.style,
            created_at: new Date().toISOString(),
            is_favorite: false
          })
        }
      } catch (e) {
        // 错误已由拦截器处理
      } finally {
        this.generating = false
      }
    },
    async loadHistory({ reset = false } = {}) {
      if (reset) {
        this.history.page = 1
        this.history.items = []
        this.history.endReached = false
      }
      if (this.history.loading || this.history.endReached) return
      this.history.loading = true
      try {
  const resp = await api.get('/api/ai/images', { params: { page: this.history.page, page_size: this.history.pageSize, favorites_only: this.history.favoritesOnly } })
        const list = resp.data || []
        if (reset) {
          this.history.items = list
        } else {
          // 去重：避免重复页再追加
          const existing = new Set(this.history.items.map(i => i.id))
          const filtered = list.filter(i => !existing.has(i.id))
          this.history.items.push(...filtered)
        }
        if (list.length < this.history.pageSize) {
          this.history.endReached = true
        } else {
          this.history.page += 1
        }
      } catch (e) {
      } finally {
        this.history.loading = false
      }
    },
    async loadStats() {
      try {
  const resp = await api.get('/api/ai/images/stats')
        this.stats = resp.data
      } catch (e) {}
    },
    async toggleFavorite(image) {
      if (!image?.id) return
      const original = image.is_favorite
      image.is_favorite = !original
      try {
  await api.post(`/api/ai/images/${image.id}/favorite`)
        // 可刷新 stats
        this.loadStats()
      } catch (e) {
        image.is_favorite = original
      }
    },
    async deleteImage(image) {
      if (!image?.id) return
      const idx = this.history.items.findIndex(i => i.id === image.id)
      try {
  await api.delete(`/api/ai/images/${image.id}`)
        if (idx !== -1) this.history.items.splice(idx, 1)
      } catch (e) {}
    },
    reuseFromHistory(image) {
      if (!image) return
      this.prompt = image.prompt
      this.style = this._reverseMapStyleLabel(image.style) || this.style
    },
    resetPromptToDerived() {
      if (this.basePromptSnapshot) this.prompt = this.basePromptSnapshot
    },
    setStyle(key) { this.style = key },
    _mapStyleToLabel(key) {
      const found = STYLE_PRESETS.find(s => s.key === key)
      return found ? found.label : key
    },
    _reverseMapStyleLabel(label) {
      const found = STYLE_PRESETS.find(s => s.label === label)
      return found ? found.key : null
    }
  }
})
